package com.wondertek.poms.common.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import lombok.extern.slf4j.Slf4j;

/**
 * 单例线程池小工具，轻量级使用，可以在小项目中通过一两句话使用线程池。
 * 使用方式：
 * 1. MyThreadPool myPool = MyThreadPool.getInstance();
 * 2. ThreadPoolExecutor executor = myPool.getSinglePool(); 多次调用获取相同线程池，可以系统中只有一个
 * 	  ThreadPoolExecutor executor = myPool.getSinglePool(10); 多次调用获取相同线程池，可以系统中只有一个
 * 3. ThreadPoolExecutor executor = myPool.getPool(); 获取新的线程池
 * @author douzi
 */
@Slf4j
public class MyThreadPool {
	private final String DEFAULT_THREAD_NAME = "DOUZI";
	private final String DEFAULT_THREAD_GROUP_NAME = "GDZ";
	private final int DEFAULT_CORE_POOL_SIZE = 1;
	private final int DEFAULT_MAX_POOL_SIZE =  2 * Runtime.getRuntime().availableProcessors() + 1;
	private final int DEFAULT_KEEP_ALIVE_SECONDS = 60;
	private final int DEFAULT_QUEUE_CAPACITY = 10000;
	/**
     * 当溢出时阻塞到队列任务数下降到队列总大小的百分比
     */
    private static final float OVERFLOW_WAIT = 0.8f;

    /**
     * 默认线程池活跃的与最大数量的比例
     */
    private static final float MAX_CORE_SIZE_RATIO = 0.5f;
	
	private ThreadPoolExecutor singlePool = null;
	
	private MyThreadPool() {
		this.singlePool = getPool();
	}
	
	private static class HolderClass {
		private static final MyThreadPool POOL = new MyThreadPool();
	}
	
	public static MyThreadPool getInstance() {
		return HolderClass.POOL;
	}
	
	public ThreadPoolExecutor getPool() {
		return getPool(DEFAULT_THREAD_NAME);
	}
	
	public ThreadPoolExecutor getPool(String threadName) {
		return getPool(threadName, DEFAULT_CORE_POOL_SIZE, DEFAULT_MAX_POOL_SIZE, DEFAULT_QUEUE_CAPACITY);
	}
	
	public ThreadPoolExecutor getPool(int maxPoolSize) {
		int corePoolSize = (int) (maxPoolSize * MAX_CORE_SIZE_RATIO);
        corePoolSize = corePoolSize == 0 ? 1 : corePoolSize;
		return getPool(DEFAULT_THREAD_NAME, corePoolSize, maxPoolSize, DEFAULT_QUEUE_CAPACITY);
	}
	
	public ThreadPoolExecutor getPool(int maxPoolSize, int queueCapacity) {
		int corePoolSize = (int) (maxPoolSize * MAX_CORE_SIZE_RATIO);
        corePoolSize = corePoolSize == 0 ? 1 : corePoolSize;
		return getPool(DEFAULT_THREAD_NAME, corePoolSize, maxPoolSize, queueCapacity);
	}
	
	public ThreadPoolExecutor getPool(int corePoolSize, int maxPoolSize, int queueCapacity) {
		return getPool(DEFAULT_THREAD_NAME, corePoolSize, maxPoolSize, queueCapacity);
	}
	
	public ThreadPoolExecutor getPool(String threadName, int corePoolSize, int maxPoolSize, int queueCapacity) {
		ThreadGroup groupName = new ThreadGroup(DEFAULT_THREAD_GROUP_NAME);
		ThreadFactory namedThreadFactory = new DefaultThreadFactoryImpl(threadName, groupName);
		
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize, DEFAULT_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(queueCapacity), namedThreadFactory, 
                new DefaultRejectedHandler(threadName, queueCapacity));
	}
	
    public ThreadPoolExecutor getSinglePool() {
		return singlePool;
	}
    
	/**
     * 关闭线程池（阻塞）
     *
     * @param executor 线程池
     */
    public void poolStopSync(ExecutorService executor) {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
            try {
                while (!executor.awaitTermination(2, TimeUnit.SECONDS)) {
                    log.debug("wait for the thread pool task to end.");
                }
            } catch (InterruptedException e) {
                log.error("close pool is error!", e);
                Thread.currentThread().interrupt();
            }
        }
    }
    
    /**
     * 立即关闭线程池
     *
     * @param executor 线程池
     */
    public void poolStopSyncNow(ExecutorService executor) {
        if (executor != null && !executor.isShutdown()) {
        	executor.shutdownNow();
        }
    }

    /**
     * 关闭线程池（非阻塞）
     *
     * @param executor 线程池
     */
    public void poolStopAsync(ExecutorService executor) {
        new Thread(() -> poolStopSync(executor)).start();
    }
    
    class DefaultThreadFactoryImpl implements ThreadFactory {
        private final String namePrefix;
        private final ThreadGroup group;
        private final AtomicLong count;

        DefaultThreadFactoryImpl(String namePrefix, ThreadGroup group) {
            this.namePrefix = namePrefix;
            this.group = group;
            this.count = new AtomicLong();
        }

        DefaultThreadFactoryImpl(String namePrefix) {
            this(namePrefix, (ThreadGroup) null);
        }

        @Override
        public Thread newThread(Runnable target) {
            return new Thread(this.group, target, this.namePrefix + "-" + this.count.incrementAndGet());
        }
    }
    
    class DefaultRejectedHandler implements RejectedExecutionHandler {
    	private int queueCapacity;
    	private String threadName;
    	
    	DefaultRejectedHandler(String threadName, int queueCapacity) {
    		this.threadName = threadName;
    		this.queueCapacity = queueCapacity;
    	}
    	
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        	try {
                while (executor.getQueue().size() > queueCapacity * OVERFLOW_WAIT) {
                    Thread.sleep(50L);
                }
            } catch (InterruptedException e) {
                log.error(threadName + ":sleep is false", e);
                Thread.currentThread().interrupt();
            }
            executor.submit(r);
        }
    }
}
